package com.zwz.crawler.annualReports;


import com.zwz.constant.Constant;
import com.zwz.entity.EnterpriseAnnualReport;
import com.zwz.parse.JsonParserUtil;
import com.zwz.vo.AccountInfo;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;



@Slf4j
public class TungReportsEmail {
    // 配置参数
//    private static final String ENTERPRISE_ID = "577de19eadf21dc4";
    private static final String API_TEMPLATE = "/api/enterprise/info/annual-report?enterprise_id=%s";

    public static AccountInfo  startTungeeAnnualReportQuery(String  ENTERPRISE_ID ) {
        AccountInfo  e1=null;
        try {
            // 构建精准URL（带参数编码保护）
            String encodedId = URLEncoder.encode(ENTERPRISE_ID, String.valueOf(StandardCharsets.UTF_8));
            String apiPath = String.format(API_TEMPLATE, encodedId);
            String fullUrl = "https://sales.tungee.com" + apiPath;

            // 发送请求
            Connection.Response response = Jsoup.connect(fullUrl)
                    .method(Connection.Method.GET)
//                    .header("Accept-Charset", "gbk")
                    // 请求头精确配置（与浏览器完全一致）
                    .header("authority", "sales.tungee.com")
                    .header("accept", "*/*")
                    .header("accept-encoding", "gzip, deflate, br, zstd")
                    .header("accept-language", "zh-CN,zh;q=0.9")
                    .header("cache-control", "no-cache")
//                    .header("cookie", getCookies()) // Cookie动态获取
                    .header("cookie", Constant.cookies) // Cookie动态获取
                    .header("pragma", "no-cache")
                    .header("priority", "u=1, i")
                    .header("referer", "https://sales.tungee.com/enterprise-details/"+ENTERPRISE_ID+"/enterprise-information/annual-reports")
                    .header("sec-ch-ua", "\"Not;A=Brand\";v=\"24\", \"Chromium\";v=\"128\"")
                    .header("sec-ch-ua-mobile", "?0")
                    .header("sec-ch-ua-platform", "\"Windows\"")
                    .header("sec-fetch-dest", "empty")
                    .header("sec-fetch-mode", "cors")
                    .header("sec-fetch-site", "same-origin")
                    .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36")
                    .header("x-tonxis-pid", "67864ea75f69e05d3b544ca7")
                    // 连接策略
                    .ignoreContentType(true)
                    .ignoreHttpErrors(true)
                    .maxBodySize(0)
                    .timeout(30000)
                    .execute();

//            response.charset("gbk"); // 替换为实际编码
            // 处理响应
            processResponse(response);

            //处理解析
            e1 = JsonParserUtil.parseReport4(response.body());
        } catch (IOException e) {
            handleNetworkException(e);
        }
        return e1;
    }

    private static String getCookies() {
        // 实际生产环境应从安全存储获取
        return "_tx_pid=67864ea75f69e05d3b544ca7; __wpkreporterwid_=cc4a07fc-7bb9-40a4-96bc-2cbac34b658f; "
                + "__last_enter_version=sales; _co_i=6805a5576eceb9637696f09d; _tx_uid=680701dddca941522b77e864; "
                + "_tx_cid=6805a5576eceb9637696f09d; DISTINCT_ID=b84fe276-099f-4932-92b3-d54b92ae384b; "
                + "_tx_sid=MTc0NTMwMTE0MzYyMjo4MmQ2OTQ5MTY0NjU2ODNmYjQ5MjlmMjc3NDg5ZDFlZg==; "
                + "Hm_lvt_f2ee75449fc055cc4dbceb4fe403bea3=1745302709,1745562840,1745562921,1745564178; HMACCOUNT=B4E402DF057C895E; "
                + "SecurityCenterDuId=ImFBSG15RzdPdVdPdCtsWnNGMFVuSXhVPSI.GuzDmQ.Pxm3uG40J8gTQGNwc2K6fX_MFS0; "
                + "remember_token=680b3219dca94151d0217627|34818d350c18319a1eeb92d5dbe213bb4b12acaa3b376797d72ad39e95e124fb0e49b10789a251113f9e7472d910d453bc4132777b1795cb3511954bea5f068a; "
                + "tg_referrer_source=https%3A%2F%2Fuser.tungee.com%2F; Hm_lpvt_f2ee75449fc055cc4dbceb4fe403bea3=1745565227; "
                + "acw_tc=1a0c380f17455680260548487e005cefc813938b38d70be876322c240c4c62; "
                + "accountCenterSessionId=.eJwljsFOwzAQRP_F5x52vU7s9AYS6oUUVQqH5BKtvWtaKQQpSWkJ4t-J4DijeaP3bfqLmL0hppADYgQlKUky5lCiomjUmD16JQ7JRgHHTp1LKXnPBGCBE1QA4HMgCcExOyQfiTMXyTubCiCO4goQjCW4ALZ0KE4t2Ky0PYsnNTuTzjyOOmwyN41bHlWln_lT--Wjl2j2mYdZd-Y66_QvXQaIZLGSxJXDAgUs-tL6DZ7_BvXh9dYduuG4PixHe7rXXwBd067Pzdu9bp62rsV2PVG9Pl5eGnnfwD5POp_Nfpmu-vML6G9U2A.GuzVTg.j_TsHe8eQXg7VPmj60nt8Frszkc; "
                + "doncusSessionId=eyJfZnJlc2giOmZhbHNlLCJ1c2VyX2lkIjoiNjgwNzAxZGRkY2E5NDE1MjJiNzdlODY0In0.GuzVZw.sGCr7W_VQPnRx2hy6Cyih6BDsdk";
    }

    private static void processResponse(Connection.Response response) {
       log.info("=== 响应状态 ===");
       log.info("URL: " + response.url());
       log.info("状态码: " + response.statusCode());

        switch (response.statusCode()) {
            case 200:
               log.info("\n=== 企业年报数据 ===");
               log.info(response.body());
                break;
            case 401:
                System.err.println("[认证失效] 需要：");
                System.err.println("1. 检查remember_token和accountCenterSessionId的有效性");
                System.err.println("2. 通过浏览器登录更新Cookie");
                break;
            case 403:
                System.err.println("[权限不足] 可能原因：");
                System.err.println("1. 当前账户无查看年报权限");
                System.err.println("2. 企业信息属于敏感数据");
                break;
            case 404:
                System.err.println("[数据不存在] 检查：");
                System.err.println("1. 企业ID是否正确: " );
                System.err.println("2. 该企业是否公开年报信息");
                break;
            case 429:
                System.err.println("[请求频繁] 建议：");
                System.err.println("1. 添加5-10秒请求间隔");
                System.err.println("2. 使用代理IP池轮换");
                break;
            default:
                System.err.println("异常响应: " + response.statusMessage());
        }
    }

    private static void handleNetworkException(IOException e) {
        System.err.println("\n=== 网络异常诊断 ===");
        if (e.getMessage().contains("timed out")) {
            System.err.println("连接超时解决方案：");
            System.err.println("1. 检查本地DNS设置（建议8.8.8.8）");
            System.err.println("2. 增加超时时间至60秒");
        } else if (e.getMessage().contains("SSL handshake")) {
            System.err.println("SSL握手失败：");
            System.err.println("1. 更新JRE的cacerts证书库");
            System.err.println("2. 添加-Djsse.enableSNIExtension=false参数");
        } else {
            System.err.println("未知网络错误：");
            e.printStackTrace();
        }
    }

    // 增强功能：自动化导出年报PDF
    public static void exportAnnualReport() {
        // 伪代码示例：
        // 1. 解析JSON响应获取下载链接
        // 2. 使用Jsoup下载PDF文件
        // 3. 保存到本地目录
    }
}